package vtt.android.cartoon_video.fragments;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import necvn.android.youtube_helper.VttYoutubeAPI;
import necvn.android.youtube_helper.entities.YoutubeItemResult;
import necvn.android.youtube_helper.entities.YoutubeSearchResult;
import vtt.android.cartoon_video.Constants;
import vtt.android.cartoon_video.R;
import vtt.android.cartoon_video.adapters.BaseListAdapter;
import vtt.android.cartoon_video.dialogs.DialogManager;
import vtt.android.library.utils.VttGA;
import vtt.android.library.utils.VttUtils;
import vtt.android.library.utils.api_helper.HTTPRequestor;
import vtt.android.library.utils.api_helper.HTTPRequestor.Listener;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

import com.google.android.gms.ads.AdView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
import com.twotoasters.jazzylistview.JazzyHelper;
import com.twotoasters.jazzylistview.JazzyListView;

import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;

/**
 * A placeholder fragment containing a simple view.
 */
public class BaseMainFragment extends BaseFragment {

    private static final String ARG_SECTION_NUMBER = "SECTION_NUMBER";
    private static final String ARG_SEARCH_KEY = "SEARCH_KEY";
    private static final String KEY_TRANSITION_EFFECT = "transition_effect";
    
    /* inject view */
    @InjectView(R.id.tv_load_more) View mBtnLoadMore;
    @InjectView(R.id.progressBar1) SmoothProgressBar mProgressBar;
    
    // search key
    private String mSearchKey;
    
    private OnItemSelectedListener listener;
    private JazzyListView mListview;
    private BaseListAdapter mAdapter;

    // item list
    private List<YoutubeItemResult> mItemList;
    // parent activity
    private Activity mParentAct;

    private int mCurrentTransitionEffect = JazzyHelper.STANDARD;
    //
    private String mNextPageToken = "";
    private boolean mIsLoadingMore;
    
    public static BaseMainFragment newInstance(int sectionNumber, String searchKey) {
        BaseMainFragment fragment = new BaseMainFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        args.putString(ARG_SEARCH_KEY, searchKey);
        fragment.setArguments(args);
        return fragment;
    }
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        mParentAct = activity;
        if (activity instanceof OnItemSelectedListener) {
            listener = (OnItemSelectedListener) activity;
        } else {
            throw new ClassCastException(activity.toString()
                    + " must implemenet BaseMainFragment.OnItemSelectedListener");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mItemList = new ArrayList<YoutubeItemResult>();
        mAdapter = new BaseListAdapter(mParentAct, mItemList);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        log.d("VTT>>> " + "onCreateView");

        View rootView = inflater.inflate(R.layout.fragment_main_list, container, false);
        ButterKnife.inject(this, rootView);
//        mBgImage = (ImageView) rootView.findViewById(R.id.img_bacground);
//        mBgImage.setImageResource(CommonHashMap.getRandomBackgroundId());

        mListview = (JazzyListView) rootView.findViewById(R.id.listview_rss);
        mListview.setAdapter(mAdapter);
        mListview.setOnScrollListener(new PauseOnScrollListener(ImageLoader.getInstance(), true, true, onScrollListener));
        mListview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                log.d("VTT>>> onItemClick ");
                YoutubeItemResult youtubeItem = (YoutubeItemResult) mAdapter.getItem(position);
                listener.onYoutubeItemSelected(youtubeItem.id.videoId);
            }
        });

        if (savedInstanceState != null) {
            mCurrentTransitionEffect = savedInstanceState.getInt(KEY_TRANSITION_EFFECT, mCurrentTransitionEffect);
        }

        if(Build.VERSION.RELEASE.contains("4.4.4")){
            mCurrentTransitionEffect = JazzyHelper.STANDARD;
        }
        
        setupJazziness(mCurrentTransitionEffect);

        // Look up the AdView as a resource and load a request.
        AdView adView = (AdView) rootView.findViewById(R.id.adView);
        loadAdmob(adView);
        
        // load youtube data
        loadYoutubeData(mNextPageToken);
        
        return rootView;
    }
    
    @OnClick(R.id.tv_load_more)
    public void onLoadMoreClicked() {
        log.d("VTT>>> onLoadMoreClicked");
        loadYoutubeData(mNextPageToken);
    }

    /**
     * load data from youtube
     * @param nextPageToken
     */
    private void loadYoutubeData(String nextPageToken) {
        log.d("VTT>>> loadYoutubeData nextPageToken " + nextPageToken);
        
        VttYoutubeAPI youItemResultAPI = new VttYoutubeAPI(mParentAct, getString(R.string.youtube_api_key));
        
        // show progress
        mProgressBar.progressiveStart();
        // begin loading data
        mIsLoadingMore = true;
        
        mSearchKey = getArguments().getString(ARG_SEARCH_KEY);
        log.i("VTT>>> mSearchKey " + mSearchKey);
        youItemResultAPI.searchData(mSearchKey, "date", nextPageToken, Constants.NUM_PER_PAGE, new HTTPRequestor(new Listener() {
            @Override
            public void onSucceed(HTTPRequestor requestor, URI uri, Object content) {
                if(getActivity() == null) {
                    return;
                }
                
                YoutubeSearchResult result = (YoutubeSearchResult) content;
                mNextPageToken = result.nextPageToken;
                
                List<YoutubeItemResult> itemList = result.items;
                //log.d("VTT>>> items " + itemList);
                
                if(itemList != null && itemList.size() > 0){
                    mItemList.addAll(itemList);
                    mAdapter.notifyDataSetChanged();
                }
                
                mBtnLoadMore.setVisibility(View.GONE);
                mProgressBar.progressiveStop();
                mIsLoadingMore = false;
            }

            @Override
            public void onFailed(HTTPRequestor requestor, URI uri, Throwable throwable) {
                log.d("VTT>>> onFailed " + throwable.getMessage());
                if(getActivity() == null) {
                    return;
                }
                mBtnLoadMore.setVisibility(View.VISIBLE);
                mIsLoadingMore = false;
                mProgressBar.progressiveStop();
                //Toast.makeText(getActivity(), getString(R.string.msg_load_data_error), 0).show();
            }
        }));
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
        inflater.inflate(R.menu.main, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        log.d("VTT>>> onOptionsItemSelected BaseMainFragment ");
        switch (item.getItemId()) {
        case R.id.action_refresh:

            if (!VttUtils.checkNetworkConnection(mParentAct)) {
                mDialogManager.showCommonDialog(DialogManager.DIALOG_TYPE_INFOR,
                        getString(R.string.msg_title_notice), getString(R.string.msg_network_error), null);
                return true;
            }
            // show progress bar
            // mProgressBar.setVisibility(View.VISIBLE);
            // change background for listview
            // mBgImage.setImageResource(CommonHashMap.getRandomBackgroundId());
            /*if(mParentAct instanceof MainActivity){
                ((MainActivity)mParentAct).changeBackground();
            }*/
            
            // reset list
            mItemList.clear();
            mAdapter.clear();
            mAdapter.notifyDataSetChanged();
            mNextPageToken = "";
            // TODO refresh
            loadYoutubeData(mNextPageToken);
            
            break;

        case R.id.action_menu_rate_app:
            VttGA.sendEvent(mParentAct, "BaseMainFragment", "Gop Y", "", 0);
            VttUtils.openGooglePlayMarket(mParentAct, mParentAct.getPackageName());
            break;

        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(KEY_TRANSITION_EFFECT, mCurrentTransitionEffect);
    }

    private void setupJazziness(int effect) {
        mCurrentTransitionEffect = effect;
        mListview.setTransitionEffect(mCurrentTransitionEffect);
    }

    // add event scroll listener
    private OnScrollListener onScrollListener = new OnScrollListener() {
        int mFirstVisibleItem = 0;
        int mVisibleItemCount = 0;
        int mTotalItemCount = Integer.MAX_VALUE;
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            // Log.v("TEST", "VTT>>> onScroll firstVisibleItem " + firstVisibleItem + "; visibleItemCount "
            // + visibleItemCount + "; totalItemCount " + totalItemCount);
            mFirstVisibleItem = firstVisibleItem;
            mVisibleItemCount = visibleItemCount;
            mTotalItemCount = totalItemCount;
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            log.d("VTT>>> onScrollStateChanged " + scrollState);
            if(scrollState == SCROLL_STATE_IDLE) {
                onScrollComplete();
            }
        }
        
        private void onScrollComplete() {
            if ((mFirstVisibleItem + mVisibleItemCount + 2) >= mTotalItemCount) {
                // TODO load more data
                if(!mIsLoadingMore) {
                    loadYoutubeData(mNextPageToken);
                }
            }
        }
    };

    public interface OnItemSelectedListener {
        /**
         * on youtube item click
         * @param video id
         */
        public void onYoutubeItemSelected(String videoId);
    }
}